/**
 * 文件相关操作
 * */
const compressing = require('compressing')
const fs = require("fs");
const fsPromise = require("fs/promises");

/**
 * 解压缩zip包*/
exports.unzip=(zipPath, targetDir)=>{
    console.log(zipPath)
    console.log(targetDir)
    return compressing.zip.uncompress(zipPath, targetDir)
        .then(() => {
            console.log('解压缩成功！')
            return {
                success: true,
                msg: '解压缩成功！'
            }
        })
        .catch(err => {
            console.log('解压缩失败！'+err)

            return {
                success: false,
                msg: '解压缩失败！'+err
            }
        })
}

/*下载文件
* filePath——下载文件地址
* fileData——写入下载文件的数据*/
exports.downloadFile=async (option)=>{
    try {
        let {filePath,fileData,fileName}=option
        console.log(filePath);
        console.log(fileData);
        // const fileData = fs.writeByFilePath(filePath)
        const writeRs=fsPromise.writeFile(filePath,fileData)
        return{
            data:writeRs,
            success:true
        }
    }catch (e){
        return{
            success:false
        }
    }
}
/*将源文件写入目标文件——复制文件*/
exports.writeByFilePath=async (option)=>{

    try {
        let {sourcePath,targetPath}=option
        if(!targetPath){
            console.log(process.env.electronAssetsPath)
            targetPath=process.env.electronAssetsPath+'\\'+'common.svga'
        }
        const fileData = fs.readFileSync(sourcePath, {encoding: 'utf8'})
        const writeFile = fsPromise.writeFile(targetPath,fileData)
        await writeFile
        return{
            success:true
        }
    }catch (e){
        console.log(e)
        return{
            success:false
        }
    }

}
/*根据路径读取文件*/
exports.readByFilePath=async (option)=>{
    try {
        let {filePath}=option
        const fileData = fs.readFileSync(filePath)
        return{
            fileData,
            success:true
        }
    }catch (e){
        return{
            success:false
        }
    }
}
